const express = require('express');
const WebSocket = require('ws');
const http = require('http');
const path = require('path');
const ginRummy = require('./gin-rummy');

const app = express();

app.use(express.static(path.join(__dirname, 'web')));

app.get('*', (_, res) => {
  res.sendFile(path.join(__dirname, 'web/index.html'));
});

const port = process.env.PORT || '3001';
app.set('port', port);

const server = http.createServer(app);

const serverCallback = () => {
  let { address, port } = server.address();
  console.log()
  if (address === '::') address = 'localhost';

  console.log(`API running on http://${address}:${port}`);
};

server.listen(port, serverCallback);

server.on('error', (err) => {
  console.log('err:');
  console.log('    Error: %s', err.toString());
  console.log('    code: %s', err.code);
  console.log('    errno: %s', err.errno);
  console.log('    syscall: %s', err.syscall);
  console.log('    address: %s', err.address);
  console.log('    port: %s', err.port);
  console.log();

  if (err.code === 'EADDRINUSE') {
    let port = err.port;
    port += 1;
    server.listen(port, serverCallback);
  }
});

const wss = new WebSocket.Server({ port: 3110 });

wss.on('connection', function (ws) {
  // 当网页发起 ws 连接，且连接协议为 ginrummy 时，初始化一个玩家
  if (ws.protocol === 'ginrummy') {
    ginRummy.initGame(ws);
  }
});